import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Alert, Form, Switch, Icon, Input, Select, Button, Row, Col, message } from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;
const TextArea = Input.TextArea;
import Chooser from 'components/chooser'
import chooserData from 'share/chooserData'
import Condition from 'components/condition'
import constants from 'share/constants'
import routeService from 'routes/route.service';
import creditManagementService from 'containers/credit-setting/credit-management/credit-management.service'
const If = Condition.If;

class CreditEventDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      data: {}
    };
  }

  componentWillReceiveProps(nextProps){
    if(nextProps.showSlideFrame && !this.props.showSlideFrame){
      let nextData = nextProps.params.data;
      let valueWillSet = this.props.form.getFieldsValue();
      Object.keys(valueWillSet).map(key => {
        valueWillSet[key] = nextData[key];
      });
      this.props.form.setFieldsValue(valueWillSet);
    }
  }

  onCancel = () => {
    this.props.close();
  };

  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.conditionId = values.creditCondition[0].id;
        values.businessCode = values.entity[0].businessCode;
        values.entityType = 1002;
        values.entityOID = values.entity[0].expenseReportOID;
        values.userOID = values.user[0].userOID;
        values.modelTypeId = 1001;
        values.operatorOID = this.props.user.userOID;
        let id = this.props.data.id;
        if(id){
          values.id = id;
        }
        delete values.creditCondition;
        delete values.entity;
        delete values.user;
        this.setState({ loading: true });
        creditManagementService.saveCreditEvents(values).then(res => {
          message.success(messages('common.operate.success')/*操作成功*/);
          this.setState({ loading: false });
          this.props.close(this.props.nowTab);
        })
      }
    });
  };

  render(){
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { loading } = this.state;
    const { data } = this.props;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 10, offset: 1 },
    };
    let creditConditionItem = JSON.parse(JSON.stringify(chooserData['credit_condition']));
    creditConditionItem.columns = chooserData['credit_condition'].columns;
    let user = getFieldValue('user');
    let userOID = (user && user.length > 0) ? user[0].userOID : null;
    let setOfBooksId = (user && user.length > 0) ? user[0].setOfBooksId : null;
    creditConditionItem.url = creditConditionItem.url.replace('{userOID}', userOID);
    let entity = getFieldValue('entity');
    let entityData = (entity && entity.length > 0) ? entity[0] : {};
    let extraParams = { jobId: entityData.applicantJobId };
    let creditCondition = getFieldValue('creditCondition');
    let condition = (creditCondition && creditCondition.length > 0) ? creditCondition[0] : {};
    return (
      <div>
        <Alert
          message={messages('common.help')/*提示信息*/}
          description={messages('credit-setting.key12')/*同一单据的同一信用事件，可在事件描述中描述多个事由，并用分号（；）区分，并选择对应的信用规则。*/}
          type="info"
          showIcon
        />
        <Form onSubmit={this.handleSave} style={{ marginTop: 30 }}>
          <FormItem {...formItemLayout} label={messages('credit-setting.key2')/*信用人*/}>
            {getFieldDecorator('user', {
              rules: [{
                required: true,
                message: messages('common.please.select')/*请选择*/
              }]
            })(
              <Chooser
                type="user"
                valueKey="userOID"
                labelKey="fullName"
                disabled={!!data.id}
                listExtraParams={{ resourceId: routeService.getResourceIdByMenu(), roleType: 'TENANT' }}
                single
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('credit-setting.key3')/*信用类型*/}> {messages('credit-setting.key13')/*报销信用*/}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('credit-setting.key4')/*相关单据*/}>
            {getFieldDecorator('entity', {
              rules: [{
                required: true,
                message: messages('common.please.select')/*请选择*/
              }]
            })(
              <Chooser
                type="expense_report"
                valueKey="businessCode"
                labelKey="businessCode"
                single
                onChange={this.onSelectApplication}
                disabled={!userOID || !!data.id}
                listExtraParams={{ userOID, setOfBooksId }}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('credit-setting.key5')/*事件描述*/}>
            {getFieldDecorator('comment', {
              rules: [{
                required: true,
                message: messages('common.please.enter')/*请输入*/
              }]
            })(
              <TextArea
                autosize={{ minRows: 2 }}
                style={{ minWidth: '100%' }}
                maxLength="500"
                placeholder={messages('common.please.enter')/*请输入*/}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('credit-setting.key6')/*信用规则*/}>
            {getFieldDecorator('creditCondition', {
              rules: [{
                required: true,
                message: messages('common.please.select')/*请选择*/
              }]
            })(
              <Chooser
                type="credit_condition"
                valueKey="id"
                labelKey="ruleCondition"
                single
                disabled={!userOID || !!data.id}
                listExtraParams={extraParams}
                selectorItem={creditConditionItem}
              />
            )}
          </FormItem>
          <If value={condition.id}>
            <FormItem {...formItemLayout} label={messages('credit-setting.key7')/*处理方式*/}>
              {constants.getTextByValue(condition.operationType, 'creditRuleOperation')}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('credit-setting.key8')/*处理结果*/}>
              {`${condition.operationType % 2 === 0 ? '-' : '+'}${condition.operationType > 1002 ? condition.changeRank : condition.changeScore}`}
            </FormItem>
          </If>
          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>{messages('common.save')/* 保存 */}</Button>
            <Button onClick={this.onCancel}>{messages('common.cancel')/* 取消 */}</Button>
          </div>
        </Form>
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    user: state.login.user
  }
}
const WrappedCreditEventDetail = Form.create()(CreditEventDetail);

export default connect(mapStateToProps)(WrappedCreditEventDetail);
